<template>
  <div>
    <el-drawer
        :model-value="visible"
        title="日报信息"
        size="800px"
        @close="closeHandle"
        @closed="closed"
    >
      <div class="demo-drawer__content">
        <el-form :model="form" ref="formRef" :rules="formRules" label-position="left">
          <el-form-item label="日报时间" :label-width="formLabelWidth">
            <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="请选择时间"
                :size="size"
            />
          </el-form-item>
          <el-form-item label="日报内容" :label-width="formLabelWidth">
            <div style="border: 1px solid #ccc">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-space>
          <el-button type="info" plain :loading="loading" @click="cancelHandle">取消</el-button>
          <el-button type="primary" :loading="loading" @click="confirmHandle">提交保存</el-button>
        </el-space>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import getConf from '@/views/news-upload/conf.js'
import {ref, reactive, computed, watch, onBeforeUnmount, shallowRef, onMounted} from "vue";
import {getUsers} from "@/api/user";
import {addProject, editProject} from "@/api/project";
import {platformInformation, platformType, uploadImage, addInformation} from '@/api/information'
import {listsnopage, addmeeting} from "@/api/service.js"
import {STATUS_ENUM} from "@/views/project-list/status";
import {toast} from "@/hook/toast";
import {delay} from "@/utils";
import store from '@/store'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import request from "@/request/index"; // 引入 css

const editorRef = shallowRef()
const valueHtml = ref('')
const toolbarConfig = {}
const FILE_LIST = ref([])

const getFilename = (src) => {
  const reg = /^[\s\S]+\/static\/([\s\S]+)$/
  const srcExec = reg.exec(src)
  if (srcExec) {
    return srcExec[1]
  }
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: getConf(
      (src) => {
        console.log(src, '上传图片的路径');
        // const name = getFilename(src)
        // console.log(name);
        // if (name) {
        // 	FILE_LIST.push(name)
        // }
      },
  ),
}


const mode = 'default'
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const form = reactive({
  xiangmu_id: '',
  date: "",
  content: "",
  editId: null,
  isEdit: false,
});
const formRules = computed(() => ({

  name: [
    {
      required: true,
      message: '请输入项目名称',
      trigger: 'change',
    }
  ],
  gongqi: [
    {
      required: true,
      message: '请输入工期',
      trigger: 'change',
    }
  ],
}))
const formRef = ref(null)
const loading = ref(false);
const radio = ref('客户资料')
// 定义上传图片数组
const fileList = ref([])
// 定义上传 文件
const fileList2 = ref([])


// token

const headerObj = ref({})
const {hasLogin, token} = store.getters
headerObj.value.token = token;

// 上传图片 后
function handleRemove(uploadFile, uploadFiles) {

}

// 查看图片
function handlePreview(file) {
}

const images = ref([])

// 上传图片后展示
function successUpdata(e) {
  images.value.push(e.data.fullurl)
}

const size = ref("default");
const formLabelWidth = "80px";
const statusEnum = computed(() => STATUS_ENUM)
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  }
})
const emits = defineEmits(['update:modelValue', 'addSuccess'])

const cancelHandle = () => {
  visible.value = false
}

function closed() {
  resetForm()
}

const imageUrl = ref('')

// 触发单选
function changeRadio(e) {
  // 选择单选完之后
  radio.value = e
  getPlatform()
}

const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emits('update:modelValue', value)
  }
})
const userList = ref([])

async function initUserList() {
  const resp = await getUsers()
  const {code, data, msg} = resp
  if (code !== 1) return
  if (!!data && data.length) {
    userList.value = data.map(item => {
      const {id, nickname} = item
      return {value: id, label: nickname}
    })
  }
}

// 获取公司列表
const company = ref([])

async function companyList() {
  const resp = await platformInformation()
  const {code, data, msg} = resp
  if (code !== 1) return
  company.value = data
}

// 获取资料
const platformTypeData = ref([])

async function getPlatform() {
  platformTypeData.value = [];
  const ziliao_type = radio.value
  const resp = await platformType({ziliao_type})
  const {code, data, msg} = resp
  if (code !== 1) return
  if (!!data && data.length) {
    platformTypeData.value = data.map(item => {
      const {id, name} = item
      return {value: id, label: name}
    })
  }
}

const ziliao_ids = ref('')

// 选择资料的时候
function changeClick(e) {
  ziliao_ids.value = e
}

// 清空数据
function resetForm() {
  form.images = []
  images.value = []
  fileList.value = []
  fileList2.value = []
  valueHtml.value = ''
  formRef.value.resetFields()
}

watch(() => props.modelValue, value => {
  if (!value) {
    form.date = null
    valueHtml.value = ''
    return
  }
  initUserList()
  companyList()
  getPlatform()
})

const closeHandle = () => {
  visible.value = false
};

function editHandle(row) {
  if (!isNaN(row)) {
    form.xiangmu_id = row
  }
  visible.value = true
  form.isEdit = false
}

defineExpose({
  editHandle,
  editRb,
})

function reqMethod(data) {
  if (form.isEdit) return editProject(data)
  return addProject(data)
}

function editRb(row) {
  visible.value = true
  form.isEdit = true
  const {html, id, date} = row
  valueHtml.value = html
  form.date = new Date(date)
  form.editId = id
  console.log(row, 'row')
}

function confirmHandle() {
  formRef.value.validate(async flag => {
    if (!flag) return
    loading.value = true
    const {xiangmu_id, date, content} = form
    const a = images.value.toString()
    const htmlVl = encodeURIComponent(valueHtml.value)
    const payload = {
      xiangmu_id, date, content: htmlVl,
    }
    console.log(form.isEdit, 'isEdit')
    if (form.isEdit && form.editId) {
      payload.id = form.editId
    }
    console.log(payload);
    const resp = await request({
      url: form.isEdit ? '/ribao/edit' : '/ribao/add',
      method: 'POST',
      data: payload
    })
    await delay(200)
    loading.value = false
    const {code, msg} = resp
    toast({title: msg})
    if (code !== 1) return
    form.isEdit = false
    form.editId = null
    triggerUpdate()
  })
}

function triggerUpdate() {
  emits('addSuccess')
  resetForm()
  visible.value = false
}
</script>
